"use client"
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { fetcher } from '@/app/libs';
import useSWR from 'swr';
import { Region } from '../../../../types/regionType';

export default function RegionEdit({ params }: { params: { id: number } }) {
    const router = useRouter();
    const { data: region, isLoading, error } = useSWR(`/region/${params.id}`, fetcher);
    const [name, setName] = useState<string>('');
    const [regionType, setRegionType] = useState<number>(0);
    const [latitude, setLatitude] = useState<number>(0);
    const [longitude, setLongitude] = useState<number>(0);
    const [parentRegionId, setParentRegionId] = useState<string | undefined>(undefined);

    useEffect(() => {
        if (region) {
            setName(region.result.Name);
            setRegionType(region.result.RegionType);
            setLatitude(region.result.Latitude);
            setLongitude(region.result.Longitude);
            setParentRegionId(region.result.ParentRegionId);
        }
    }, [region, isLoading]);

    const updateRegion = async (e: any) => {
        e.preventDefault();
        if (name !== '' && regionType !== 0 && latitude !== 0 && longitude !== 0) {
            const formData: Region = {
                ID: params.id,
                Name: name,
                RegionType: regionType,
                Latitude: latitude,
                Longitude: longitude,
                ParentRegionId: parentRegionId,
            };
            const res = await fetch(`/region/${params.id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData),
            });
            const content = await res.json();
            if (content.success > 0) {
                router.push('/region');
            }
        }
    };

    if (isLoading) return <div><span>Loading...</span></div>;
    if (!region) return null;
    return (
        <form className='w-full' onSubmit={updateRegion}>
            <span className='font-bold text-yellow-500 py-2 block underline text-2xl'>Form Edit</span>
            <div className='w-full py-2'>
                <label htmlFor="" className='text-sm font-bold py-2 block'>Name</label>
                <input type='text' name='name' className='w-full border-[1px] border-gray-200 p-2 rounded-sm' value={name} onChange={(e: any) => setName(e.target.value)} />
            </div>
            <div className='w-full py-2'>
                <label htmlFor="" className='text-sm font-bold py-2 block'>Region Type</label>
                <input type="number" name="regionType" className='w-full border-[1px] border-gray-200 p-2 rounded-sm' value={regionType} onChange={(e: any) => setRegionType(parseInt(e.target.value))} />
            </div>
            <div className='w-full py-2'>
                <label htmlFor="" className='text-sm font-bold py-2 block'>Latitude</label>
                <input type="number" name="latitude" className='w-full border-[1px] border-gray-200 p-2 rounded-sm' value={latitude} onChange={(e: any) => setLatitude(parseFloat(e.target.value))} />
            </div>
            <div className='w-full py-2'>
                <label htmlFor="" className='text-sm font-bold py-2 block'>Longitude</label>
                <input type="number" name="longitude" className='w-full border-[1px] border-gray-200 p-2 rounded-sm' value={longitude} onChange={(e: any) => setLongitude(parseFloat(e.target.value))} />
            </div>
            <div className='w-full py-2'>
                <label htmlFor="" className='text-sm font-bold py-2 block'>Parent Region ID</label>
                <input type="text" name="parentRegionId" className='w-full border-[1px] border-gray-200 p-2 rounded-sm' value={parentRegionId} onChange={(e: any) => setParentRegionId(e.target.value)} />
            </div>
            <div className='w-full py-2'>
                <button className="w-20 p-2 text-white border-gray-200 border-[1px] rounded-sm bg-green-400">Submit</button>
            </div>
        </form>
    );
}